package cc.rboot.topic.core;

import cc.rboot._core.holder.AppContextHolder;
import cc.rboot.topic.annotation.MessageTopic;
import org.springframework.core.env.Environment;

public class BaseMessageTopic<T> implements IMessageTopic<T>{

    private volatile IMessageProcessor<T> processor;

    @Override
    public String name() {
        MessageTopic messageTopic = this.getClass().getAnnotation(MessageTopic.class);
        Environment environment = AppContextHolder.getBean(Environment.class);
        String topicPrefix = environment.getProperty("rboot.topic.prefix");
        return topicPrefix + ":" + messageTopic.name();
    }

    /**
     * 返回一个单例的processor
     * 每个topic实例只允许有一个processor实例
     *
     * @return
     */
    @Override
    public IMessageProcessor<T> processor() {
        if (this.processor == null) {
            synchronized (this) {
                if (this.processor == null) {
                    MessageTopic messageTopic = this.getClass().getAnnotation(MessageTopic.class);
                    try {
                        this.processor = messageTopic.processor().newInstance();
                        this.processor.setTopic(this.name());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return this.processor;
    }

    @Override
    public void registerConsumers(IMessageConsumer<T> consumer) {
        this.processor().register(consumer);
    }

    @Override
    public void send(T message) throws Exception {
        this.processor().send(message);
    }
}
